<?php
/**
 * Created by PhpStorm
 * User: lcz
 * Date: 2019/10/15
 * Time: 9:50
 * 签到
 */

namespace app\api\controller;

use app\common\controller\Api;
use think\console\command\make\Model;
use think\Db;
use think\Exception;

class Sign extends Api {
	
	/**
	 * 签到记录
	 */
	public function index() {
		$page = $this->request->post('page', 1, 'intval');
		
		$userId = $this->auth->id;
		
		$where['user_id'] = $userId;
		
		$total = Db::name('sign')->where($where)->count();
		$list = Db::name('sign')->where($where)
			->page($page)
			->order('create_time desc')
			->field('point, from_unixtime(create_time, \'%Y-%m-%d\') as date')
			->select();
		
		$this->success('查询成功', [
			'page' => $page,
			'list' => $list,
			'total' => $total
		]);
	}
	
	
	/**
	 * 获取设置及签到情况
	 */
	
	public function setting() {
		$setting = Db::name('signSetting')
			->field('sign_start_time, from_unixtime(sign_start_time, \'%H:%i\') as start_time, sign_end_time, from_unixtime(sign_end_time, \'%H:%i\') as end_time')
			->find();
		
		$signStatus = 0;
		$sign = Db::name('sign')
			->where(['user_id' => $this->auth->id, 'create_time' => ['gt', strtotime(date('Y-m-d'))]])
			->find();
		
		$startTime = strtotime(date('H:i', $setting['sign_start_time']));
		$endTime = strtotime(date('H:i', $setting['sign_end_time']));
		$time = strtotime(date('H:i'));
		if($sign) {
			$signStatus = 1;
		}elseif($time < $startTime || $time > $endTime)
		{
			$signStatus = 2;
		}
		$this->success('查询成功', [
			'setting' => $setting,
			'status' => $signStatus
		]);
	}
	
	/**
	 * 打卡
	 */
	public function sign() {
		$userId = $this->auth->id;
		$model = new \app\common\model\Sign();
		$row = $model->where([
			'user_id' => $userId,
			'create_time' => ['gt', strtotime(date('Y-m-d'))]
		])->find();
		
		if($row) {
			$this->error('你今天已签到');
		}
		
		$res = $model->sign($userId);
		if($res) {
			$this->success('签到成功', $res);
		} else {
			$this->error('签到出错');
		}
		
		
		
	}
}
